<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件上传</title>
</head>

<body>
    <div>
        <h1>实现文件上传功能</h1>
    </div>
    <div class="page-container">
        <!-- <input type="file" id="fileInput" name="file">
        <button type="submit">上传</button> -->
        <!-- enctype：指定表单数据的编码类型，常用于文件上传 -->
        <!-- application/x-www-form-urlencoded: 默认值，适合文本数据 -->
        <!-- multipart/form-data：适合文件上传 -->
        <form action="#" method="POST" name="综合表单" enctype="multipart/form-data" id="myForm">
            <div>
                <label for="username">用户名</label>
                <input type="text" id="userName" name="userName" />
            </div>
            <div>
                <label for="password">密码</label>
                <input type="password" id="password" name="password" />
            </div>
            <div>
                <label for="submitMovice">上传电影</label>
                <input type="file" id="moviceFile" name="moviceFile">
            </div>
            <div>
                <button type="submit">上传</button>
            </div>
        </form>        
        <div>进度</div>
        <div id="progress"></div>
        <div>输出</div>
        <div id="output"></div>        
    </div>
</body>
<script>
    document.getElementById('moviceFile').addEventListener('change', function (event) {
        console.log('event.target:')
        console.dir(event.target)
        let info = '',
            output = document.getElementById("output"),
            progress = document.getElementById("progress"),
            files = event.target.files,
            type = "default",
            reader = new FileReader();

        if (/image/.test(files[0].type)) {
            reader.readAsDataURL(files[0])
            type = "image"
        } else {
            reader.readAsText(files[0])
            type = "text"
        }

        reader.onerror = function (error) {
            console.log('error:', error)
        }

        reader.onprogress = function (event) {
            if (event.lengthComputable) {
                progress.innerHTML = `${event.loaded}/${event.total}\n${event.loaded / event.total * 100}%`
            }
        }

        reader.onload = function () {
            let html = ""
            switch (type) {
                case "image":
                    html = `<img src=${reader.result}>`;
                    break
                case "text":
                    html = reader.result
                    break
            }
            output.innerHTML = html            
        }
    })
</script>

</html>